import qs from 'qs'
import { exportFile } from './exportFile'
import { requestList } from './awaitHelper'

/**
 * 延迟添加dom元素
 */
const timerTable = {}
export function setListDelay (name, data, target, time = 500, cb) {
  if (!target) return false
  if (timerTable[name] && timerTable[name].length) timerTable[name].forEach(id => clearTimeout(id))
  for (let i = target.length; i--;) {
    target.splice(i)
  }

  const eachTime = time / data.length
  let delay = 0
  timerTable[name] = []
  let isFull = false
  let temp = []

  data.forEach((item, index) => {
    if (delay < time) {
      delay += eachTime
    } else {
      isFull = true
      temp = data.splice(index)
    }
    timerTable[name].push(
      setTimeout(() => {
        !isFull && target.push(item)
        if (index === data.length - 1) {
          target.push(...temp)
          delete timerTable[name]
          cb && cb()
        }
      }, delay)
    )
  })
}

// NumberToChinese
var chnNumChar = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']
var chnUnitSection = ['', '万', '亿', '万亿', '亿亿']
var chnUnitChar = ['', '十', '百', '千']

function SectionToChinese (section) {
  var strIns = ''
  var chnStr = ''
  var unitPos = 0
  var zero = true
  while (section > 0) {
    var v = section % 10
    if (v === 0) {
      if (!zero) {
        zero = true
        chnStr = chnNumChar[v] + chnStr
      }
    } else {
      zero = false
      strIns = chnNumChar[v]
      strIns += chnUnitChar[unitPos]
      chnStr = strIns + chnStr
    }
    unitPos++
    section = Math.floor(section / 10)
  }
  return chnStr
}

export function NumberToChinese (num) {
  var unitPos = 0
  var strIns = ''
  var chnStr = ''
  var needZero = false

  if (num === 0) {
    return chnNumChar[0]
  }

  while (num > 0) {
    var section = num % 10000
    if (needZero) {
      chnStr = chnNumChar[0] + chnStr
    }
    strIns = SectionToChinese(section)
    strIns += (section !== 0) ? chnUnitSection[unitPos] : chnUnitSection[0]
    chnStr = strIns + chnStr
    needZero = (section < 1000) && (section > 0)
    num = Math.floor(num / 10000)
    unitPos++
  }
  return chnStr
}

export function chineseToNumber (str) {
  const index = chnNumChar.indexOf(str)
  if (index > -1) return index
  return str
}

export function timeFix () {
  const time = new Date()
  const hour = time.getHours()
  return hour < 9 ? '早上好' : hour <= 11 ? '上午好' : hour <= 13 ? '中午好' : hour < 20 ? '下午好' : '晚上好'
}

export function welcome () {
  const arr = ['休息一会儿吧', '准备吃什么呢?', '加班辛苦啦！别太累哦', '我猜你可能累了']
  const index = Math.floor(Math.random() * arr.length)
  return arr[index]
}

/**
 * 触发 window.resize
 */
export function triggerWindowResizeEvent () {
  const event = document.createEvent('HTMLEvents')
  event.initEvent('resize', true, true)
  event.eventType = 'message'
  window.dispatchEvent(event)
}

export function handleScrollHeader (callback) {
  let timer = 0

  let beforeScrollTop = window.pageYOffset
  callback = callback || function () {}
  window.addEventListener(
    'scroll',
    event => {
      clearTimeout(timer)
      timer = setTimeout(() => {
        let direction = 'up'
        const afterScrollTop = window.pageYOffset
        const delta = afterScrollTop - beforeScrollTop
        if (delta === 0) {
          return false
        }
        direction = delta > 0 ? 'down' : 'up'
        callback(direction)
        beforeScrollTop = afterScrollTop
      }, 50)
    },
    false
  )
}

/**
 * Remove loading animate
 * @param id parent element id or class
 * @param timeout
 */
export function removeLoadingAnimate (id = '', timeout = 1500) {
  if (id === '') {
    return
  }
  setTimeout(() => {
    document.body.removeChild(document.getElementById(id))
  }, timeout)
}

export function getUrlKey (name) {
  return decodeURIComponent(
    // eslint-disable-next-line no-sparse-arrays
    (new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ''])[1].replace(/\+/g, '%20')) || null
}

// handle params util
export function hp (data) {
  for (var key in data) {
    if (data[key] === '') {
      delete data[key]
    }
  }
  return qs.stringify(data)
}

// handle params util,not delete the null parameter
export function hpn (data) {
  return qs.stringify(data)
}

/**
 * 生成指定长度的 uuid
 * @param {Number} len 长度
 * @param {Number} radix 进制显示 2:二进制格式(0101), 10:十进制格式(1234), 16:十六进制格式(0F1A)
 */
export function uuid (len = 10, radix = 16) {
  var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
  var uuid = []; var i
  radix = radix || chars.length

  if (len) {
    // Compact form
    for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix]
  } else {
    // rfc4122, version 4 form
    var r

    // rfc4122 requires these characters
    uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
    uuid[14] = '4'

    // Fill in random data.  At i==19 set the high bits of clock sequence as
    // per rfc4122, sec. 4.1.5
    for (i = 0; i < 36; i++) {
      if (!uuid[i]) {
        r = 0 | Math.random() * 16
        uuid[i] = chars[(i === 19) ? (r & 0x3) | 0x8 : r]
      }
    }
  }

  return uuid.join('')
}

/**
 * 过滤对象中为空的属性
 * @param obj
 * @returns {*}
 */
export function filterObj (obj) {
  if (!(typeof obj === 'object')) {
    return
  }

  for (var key in obj) {
    if (obj.hasOwnProperty(key) &&
      (obj[key] == null || obj[key] === undefined || obj[key] === '')) {
      delete obj[key]
    }
  }
  return obj
}

/**
 * 切换页面 sending 变量
 * @param {Boolean} bool
 */
function toggleSending (bool) {
  this.sending = !!bool
}

/**
 * 分页处理，换页
 */

function handlePage (pageNum = 1) {
  const { queryParam = {}, refresh = () => {} } = this
  Object.assign(queryParam, { pageNum })
  refresh()
}

/**
 * 获取七牛云token
 */
function getQinuiToken () {
  const { $axios, $get } = this
  return new Promise((resolve, reject) => {
    $axios.get('jy/common/getQiniuTokenAndUrl').then(res => resolve($get(res, 'data.data', ''))).catch(e => resolve(''))
  })
}

/**
 * 上传图片
 */
function uploadImage (token, { file, onError, onSuccess }) {
  const { $message, $axios, $get } = this
  return new Promise((resolve, reject) => {
    if (!file) return $message.error('无法上传')

    const handleError = () => {
      onError && onError()
      $message.error('请稍后再试')
      resolve('')
      return false
    }

    const formData = new FormData()
    formData.append('token', token.token)
    formData.append('file', file)
    formData.append('Content-Type', 'multipart/form-data')

    $axios.post('qiniuUpload/', formData).then(res => {
      const key = $get(res, 'data.key', '')
      if (key) {
        const url = `${token.cdn}${key}`
        onSuccess && onSuccess(url)
        resolve(url)
      } else handleError()
    }).catch(e => handleError)
  })
}

export function weekInChinese (weekDay) {
  const map = { 0: '星期日', 1: '星期日', 2: '星期一', 3: '星期二', 4: '星期三', 5: '星期四', 6: '星期五', 7: '星期六' }
  return map[weekDay]
}
export {
  exportFile,
  requestList,
  toggleSending,
  handlePage,
  getQinuiToken,
  uploadImage
}
